//
//  ZGSSearchListViewController.m
//  MapleLeaf
//
//  Created by dllo on 15/11/27.
//  Copyright © 2015年 AntennaBabyTeam. All rights reserved.
//

#import "ZGSSearchListViewController.h"
#import "ZGSTypeModel.h"
#import "ZGSHomeCartoonModel.h"
#import "ZGSCartoonCell.h"
#import "ZGSCartoonDetailsViewController.h"
@interface ZGSSearchListViewController ()<UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UIView *headBgView;
@property (nonatomic, retain) UITextField *search;
@property (nonatomic, retain) NSMutableArray *listArr;
@property (nonatomic, retain) MBProgressHUD *hud;
@property (nonatomic, retain) UILabel *noneLabel;
@property (nonatomic, assign) NSInteger page;
@end

@implementation ZGSSearchListViewController


- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBarHidden = YES;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.hidden = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self createData];
    
    
}



- (void)createData {
    AFNetworkReachabilityManager *netManager = [AFNetworkReachabilityManager sharedManager];
    [netManager startMonitoring];
    [netManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == 1 || status == 2) {
        
            self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            NSString *strURL = [NSString string];
            NSString *str = [NSString stringWithFormat:@"http://api.youqudao.com/mhapi/api/list/search?market=20&customerId=1913463&uuid=64:b4:73:28:fd:2c&keyWord=%@&startIndex=0&size=20&categoryId=-1&appversion=21", self.keyWord];
            strURL = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

            [BaseAFN GETURLByString:strURL AFNData:^(id result) {
                [self createViews];
                //判断搜索结果
                if ([result[@"code"] isEqualToNumber:@101]) {
                    NSMutableArray *arr = result[@"data"][@"list"];
                    self.listArr = [NSMutableArray array];
                    self.listArr = [ZGSHomeCartoonModel baseModelByArr:arr];
                    
                    //搜索解雇
                    if (self.listArr.count > 0) {
                        self.search.placeholder = [NSString stringWithFormat:@"搜索成功%ld个搜索结果", self.listArr.count];
                        [self.noneLabel removeFromSuperview];
                        self.tableView.hidden = NO;
                    }else {
                        self.search.placeholder = @"0个搜索结果";
                        self.tableView.hidden = YES;
                        self.noneLabel.hidden = NO;
                    }
                    
                }else {
                    self.search.placeholder = @"0个搜索结果";
                    self.tableView.hidden = YES;
                    self.noneLabel.hidden = NO;
                    
                    [self.hud removeFromSuperview];
                    [self.tableView reloadData];

                    
                }
                [self.hud removeFromSuperview];
                [self.tableView reloadData];
                
                
                
                
            }];
        }else {
            [self createViews];
            [self.hud removeFromSuperview];
            MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
            [self.view addSubview:hud];
            hud.mode = MBProgressHUDModeText;
            hud.labelText = @"数据请求失败, 请检查网络后重试";
            
            [hud showAnimated:YES whileExecutingBlock:^{
                
                sleep(1);
            } completionBlock:^{
               
                [hud removeFromSuperview];
                
            }];
        }
        
    }];
}

- (void)createNewDate {
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString *strURL = [NSString string];
    NSString *str = [NSString stringWithFormat:@"http://api.youqudao.com/mhapi/api/list/search?market=20&customerId=1913463&uuid=64:b4:73:28:fd:2c&keyWord=%@&startIndex=0&size=20&categoryId=-1&appversion=21", self.keyWord];
    strURL = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    [BaseAFN GETURLByString:strURL AFNData:^(id result) {
       //判断搜索结果
        if ([result[@"code"] isEqualToNumber:@101]) {
            NSMutableArray *arr = result[@"data"][@"list"];
            self.listArr = [NSMutableArray array];
            self.listArr = [ZGSHomeCartoonModel baseModelByArr:arr];
            
            //搜索结果
            if (self.listArr.count > 0) {
                self.search.placeholder = [NSString stringWithFormat:@"搜索成功 %ld个搜索结果", self.listArr.count];
                [self.noneLabel removeFromSuperview];
                self.tableView.hidden = NO;
            }else {
                self.search.placeholder = @"0个搜索结果";
                self.tableView.hidden = YES;
                self.noneLabel.hidden = NO;
            }
        }else {
            self.search.placeholder = @"0个搜索结果";
            self.tableView.hidden = YES;
            self.noneLabel.hidden = NO;
            
            [self.hud removeFromSuperview];
            [self.tableView reloadData];

        }
        [self.hud removeFromSuperview];
        [self.tableView reloadData];

        
        
    }];
}


#pragma mark - createViews

- (void)createViews {
    
    self.headBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 64)];
    self.headBgView.backgroundColor = [UIColor colorWithRed:0.961f green:0.325f blue:0.173f alpha:1.00f];
    [self.view addSubview:self.headBgView];
    
    // 搜索栏
    self.search = [[UITextField alloc] initWithFrame:CGRectMake(50, 28, WIDTH - 120, 28)];
    self.search.backgroundColor = [UIColor whiteColor];
    self.search.layer.cornerRadius = 5;
    self.search.layer.masksToBounds = YES;
    self.search.textAlignment = NSTextAlignmentCenter;
    self.search.returnKeyType = UIReturnKeySearch;
    self.search.delegate = self;
    [self.search addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventEditingDidEndOnExit];
    [self.headBgView addSubview:self.search];
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [backButton setBackgroundImage:[UIImage imageNamed:@"iconfont-fanhui2.png"] forState:UIControlStateNormal];
    backButton.frame = CGRectMake(10, 31, 20, 23);
    [backButton addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.headBgView addSubview:backButton];
    
    UIButton *searchButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [searchButton setTitle:@"搜索" forState:UIControlStateNormal];
    searchButton.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:16];
    searchButton.tintColor = [UIColor whiteColor];
    searchButton.frame = CGRectMake(WIDTH - 55, 28, 40, 28);
    [searchButton addTarget:self action:@selector(searchBAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.headBgView addSubview:searchButton];
    
    // 搜索结果为空
    self.noneLabel = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH / 2 - 70, HEIGHT / 2 - 20 * HEIGHT / 667.0, 140, 30)];
    self.noneLabel.text = @"没有你想要搜索的内容";
    self.noneLabel.hidden = YES;
    self.noneLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.noneLabel];
}

- (UITableView *)tableView {
    
    if (!_tableView) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT - 64) style:UITableViewStylePlain];
        _tableView.separatorStyle = NO;
        _tableView.rowHeight = HEIGHT / 5.0;
        [self.view addSubview:_tableView];
        
        [self.tableView registerClass:[ZGSCartoonCell class] forCellReuseIdentifier:@"listReuse"];
        
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }
    
    return _tableView;
}

#pragma mark - tableViewDateSoure & Delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.listArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZGSCartoonCell *cell = [tableView dequeueReusableCellWithIdentifier:@"listReuse" forIndexPath:indexPath];
    
    ZGSHomeCartoonModel *cartoon =self.listArr[indexPath.row];
    // 转码
    NSString *encodingString = [cartoon.coverPic stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [cell.picView sd_setImageWithURL:[NSURL URLWithString:encodingString] placeholderImage:[UIImage imageNamed:@"backgroundImage.png"]];
    
    NSString *name = cartoon.name;
    // 关键字高亮
    NSMutableAttributedString *attName = [[NSMutableAttributedString alloc] initWithString:name];
    for (NSInteger i = 0; i < self.keyWord.length; i++) {
        NSString *tempStr = [self.keyWord substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [name rangeOfString:tempStr];
        [attName addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
    }
    
    //    if (self.keyWord.length > 2) {
    //        for (NSInteger i = 0; i < self.keyWord.length - 1; i++) {
    //            NSString *tempStr = [self.keyWord substringWithRange:NSMakeRange(i, 2)];
    //            NSRange range = [name rangeOfString:tempStr];
    //            [attName addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
    //        }
    //    }
    
    for (NSInteger i = 0; i < self.keyWord.length - 1; i++) {
        NSString *tempStr = [self.keyWord substringWithRange:NSMakeRange(i, 2)];
        NSRange range = [name rangeOfString:tempStr];
        [attName addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
    }
    
    cell.titleLabel.attributedText = attName;
    
    NSString *author = cartoon.author;
    NSMutableAttributedString *attAuthor = [[NSMutableAttributedString alloc] initWithString:author];
    for (NSInteger i = 0; i < self.keyWord.length; i++) {
        NSString *tempStr = [self.keyWord substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [author rangeOfString:tempStr];
        [attAuthor addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
    }
    
    for (NSInteger i = 0; i < self.keyWord.length - 1; i++) {
        NSString *tempStr = [self.keyWord substringWithRange:NSMakeRange(i, 2)];
        NSRange range = [author rangeOfString:tempStr];
        [attAuthor addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
    }
    
    cell.authorLabel.attributedText = attAuthor;
    
    // 更新数高亮
    NSInteger length = [cartoon.updateSize stringValue].length;
    NSString *totalString = [NSString stringWithFormat:@"更新至%@话(连载中)", cartoon.updateSize];
    NSMutableAttributedString *tMutaString = [[NSMutableAttributedString alloc] initWithString:totalString];
    [tMutaString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(3,length)];
    cell.totalLabel.attributedText = tMutaString;
    
    // 热度
    NSString *popularString = [NSString stringWithFormat:@"☆%@", cartoon.popular];
    NSMutableAttributedString *pMutaString = [[NSMutableAttributedString alloc] initWithString:popularString];
    [pMutaString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,1)];
    cell.popularLabel.textAlignment = NSTextAlignmentRight;
    cell.popularLabel.attributedText = pMutaString;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ZGSCartoonDetailsViewController * cdVC = [[ZGSCartoonDetailsViewController alloc] init];
    ZGSHomeCartoonModel *cartoon = self.listArr[indexPath.row];
    cdVC.albumId = cartoon.albumId;
    [self.navigationController pushViewController:cdVC animated:YES];
}



#pragma mark - buttonAction

- (void)backAction:(UIButton *)button {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)searchAction:(UITextField *)textField {
    
    NSString *searchStr = self.search.text;
    while ([searchStr hasPrefix:@" "]) {
        searchStr = [searchStr substringFromIndex:1];
    }
    
    if ([searchStr isEqualToString:@""]) {
        MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:hud];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"搜索框为空";
        hud.margin = 10 * HEIGHT / 667.0;
        
        [hud showAnimated:YES whileExecutingBlock:^{
            sleep(1.5);
        } completionBlock:^{
            [hud removeFromSuperview];
        }];
    }
    else {
        self.keyWord = searchStr;
        [self createNewDate];
    }
}

- (void)searchBAction:(UIButton *)button {
    
    NSString *searchStr = self.search.text;
    while ([searchStr hasPrefix:@" "]) {
        searchStr = [searchStr substringFromIndex:1];
    }
    
    if ([searchStr isEqualToString:@""]) {
        MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:hud];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"搜索框为空";
        hud.margin = 10 * HEIGHT / 667.0;
        
        [hud showAnimated:YES whileExecutingBlock:^{
            sleep(1.5);
        } completionBlock:^{
            [hud removeFromSuperview];
        }];
    }
    else {
        self.keyWord = searchStr;
        [self createNewDate];
    }
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
